package com.clusterswisdom.horn.api.tmall.action.refund;

import com.alibaba.fastjson.JSONObject;
import com.clusterswisdom.horn.api.ioc.HornAction;
import com.clusterswisdom.horn.api.ioc.HornResponse;
import com.clusterswisdom.horn.api.ioc.api.ApiConfig;
import com.clusterswisdom.horn.api.tmall.TmallInstance;
import com.clusterswisdom.horn.api.tmall.action.AbstractTmallAction;
import com.taobao.api.TaobaoResponse;
import com.taobao.api.domain.Refund;
import com.taobao.api.response.LogisticsAddressSearchResponse;
import com.taobao.api.response.RefundGetResponse;

public class RefundAgreeAction extends AbstractTmallAction implements HornAction{
	public static final String REASE = "七天无理由退换货";

	@Override
	public HornResponse execute(ApiConfig config, JSONObject param) throws Exception {
		
		Refund ref = getRefund(param);
		param.put("refund_version", ref.getRefundVersion());
		
		TaobaoResponse response = null;
		if("Y".equals(param.getString("refundRes"))){
			if (needRefundGod(ref) && RefundStatus.WAIT_SELLER_AGREE.getValue().equals(ref.getStatus())) {
				//主动查询获取退货地址
				LogisticsAddressSearchResponse addr = (LogisticsAddressSearchResponse)TmallInstance.getInstance().executeRequest(new JSONObject(), "logistics", "addressSearch");
				//卖家收货地址ID， 填入
				param.put("seller_address_id", addr.getAddresses().get(0).getAreaId());
				param.put("remark", "没有问题，同意退货");
				// 先同意退货
				TmallInstance.getInstance().executeRequest(param, "refund", "rpReturngoodsAgree");
			}
			
			reviewRefund(param);
			response = agreeRefund(param, ref);
			
		}else{
			
			
		}
		
		return new HornResponse(true, ref.getDesc());
	}
	protected Refund getRefund(JSONObject param) throws Exception{
		RefundGetResponse resp = (RefundGetResponse) TmallInstance.getInstance().executeRequest(param, "refund", "refundGet");
		return resp.getRefund();
	}
	private boolean needRefundGod(Refund refund) {
		return (refund.getHasGoodReturn() != null && refund.getHasGoodReturn().booleanValue()) || REASE.equals(refund.getReason());
	}
	
	protected TaobaoResponse agreeRefund(JSONObject param, Refund refund) throws Exception {
		String order = param.getString("refund_id")+ "|";
		order += (int)(Double.parseDouble(refund.getRefundFee()) * 100) + "|";	//订单金额
		order += refund.getRefundVersion() + "|";	//退款最后更新时间戳
		order += "onsale";	//退款阶段，固定
		param.put("refund_infos", order);
		
		TaobaoResponse response = TmallInstance.getInstance().executeRequest(param, "refund", "rpRefundsAgree");
		return response;
	}
	
	private TaobaoResponse reviewRefund(JSONObject param) throws Exception {
		param.put("operator", "审核人");
		param.put("message", "同意退款");
		param.put("result", true);
		return TmallInstance.getInstance().executeRequest(param, "refund", "rpRefundReview");
	}
}
